<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import { api } from '@/utils/request'

const auth = useAuthStore()

// 用户列表数据
const users = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const searchQuery = ref('')

// 会员等级选项
const memberLevels = ref<any[]>([])

// 编辑用户等级的模态框
const editingUser = ref<any>(null)
const showEditModal = ref(false)
const selectedLevel = ref('')

// 获取会员等级列表
async function fetchMemberLevels() {
  try {
    const res = await api.get('/api/admin/member-levels')
    if (res.ok) {
      memberLevels.value = await res.json()
    }
  } catch (err) {
    console.error('获取会员等级失败:', err)
  }
}

// 获取用户列表
async function fetchUsers() {
  try {
    loading.value = true
    const params = new URLSearchParams({
      page: String(currentPage.value),
      limit: '20'
    })

    if (searchQuery.value.trim()) {
      params.append('search', searchQuery.value.trim())
    }

    const res = await api.get(`/api/admin/users?${params}`)
    if (res.ok) {
      const data = await res.json()
      users.value = data.users || []
      totalPages.value = Math.ceil((data.total || 0) / 20)
    }
  } catch (err) {
    console.error('获取用户列表失败:', err)
    alert('사용자 목록을 가져오는데 실패했습니다')
  } finally {
    loading.value = false
  }
}

// 搜索用户
function searchUsers() {
  currentPage.value = 1
  fetchUsers()
}

// 打开编辑等级模态框
function openEditModal(user: any) {
  editingUser.value = user
  selectedLevel.value = user.memberLevel || 'regular'
  showEditModal.value = true
}

// 关闭编辑模态框
function closeEditModal() {
  editingUser.value = null
  selectedLevel.value = ''
  showEditModal.value = false
}

// 更新用户等级
async function updateUserLevel() {
  if (!editingUser.value) return

  try {
    const res = await api.put(`/api/admin/users/${editingUser.value.id}/member-level`, {
      memberLevel: selectedLevel.value
    })

    if (res.ok) {
      alert('회원 등급이 성공적으로 업데이트되었습니다')
      closeEditModal()
      fetchUsers() // 刷新列表
    } else {
      const err = await res.json().catch(() => ({}))
      alert(err?.error || '등급 업데이트에 실패했습니다')
    }
  } catch (err) {
    console.error('등급 업데이트 실패:', err)
    alert('네트워크 오류가 발생했습니다')
  }
}

// 获取等级显示名称
function getLevelName(level: string): string {
  const levelObj = memberLevels.value.find(l => l.value === level)
  return levelObj?.name || '일반회원'
}

// 翻页
function goToPage(page: number) {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    fetchUsers()
  }
}

onMounted(async () => {
  // 检查是否为管理员
  if (!auth.user) await auth.fetchMe()

  if (!auth.user || auth.user.role !== 'admin') {
    alert('관리자만 접근할 수 있습니다')
    return
  }

  await fetchMemberLevels()
  await fetchUsers()
})
</script>

<template>
  <div class="layout">
    <div class="admin-header">
      <div class="header-content">
        <h1>관리자 패널</h1>
        <button class="back-btn" @click="$router.push('/')">← 메인으로</button>
      </div>
    </div>

    <div class="admin-layout">
      <!-- 관리자 사이드바 -->
      <aside class="admin-sidebar">
        <nav class="admin-nav">
          <div class="nav-item active">
            <span class="nav-icon">👥</span>
            <span class="nav-label">회원 관리</span>
          </div>
        </nav>
      </aside>

      <!-- 메인 컨텐츠 -->
      <main class="admin-main">
      <div class="header">
        <h1>사용자 관리</h1>
        <div class="search-box">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="이메일로 검색..."
            @keyup.enter="searchUsers"
          />
          <button @click="searchUsers">검색</button>
        </div>
      </div>

      <div class="users-table" v-if="!loading">
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>로그인 ID</th>
              <th>이메일</th>
              <th>이름</th>
              <th>회원 등급</th>
              <th>상태</th>
              <th>가입일</th>
              <th>작업</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.loginId }}</td>
              <td>{{ user.email }}</td>
              <td>{{ user.name || '-' }}</td>
              <td>
                <span class="level-badge">{{ getLevelName(user.memberLevel) }}</span>
              </td>
              <td>{{ user.status === 'active' ? '활성' : '비활성' }}</td>
              <td>{{ new Date(user.createdAt).toLocaleDateString() }}</td>
              <td>
                <button class="btn-edit" @click="openEditModal(user)">등급 수정</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-if="loading" class="loading">로딩 중...</div>

      <!-- 分页 -->
      <div class="pagination" v-if="totalPages > 1">
        <button
          @click="goToPage(currentPage - 1)"
          :disabled="currentPage <= 1"
        >
          이전
        </button>
        <span>{{ currentPage }} / {{ totalPages }}</span>
        <button
          @click="goToPage(currentPage + 1)"
          :disabled="currentPage >= totalPages"
        >
          다음
        </button>
        </div>
      </main>
    </div>

    <!-- 编辑等级模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click.self="closeEditModal">
      <div class="modal">
        <div class="modal-header">
          <h3>회원 등급 수정</h3>
          <button class="close-btn" @click="closeEditModal">✕</button>
        </div>
        <div class="modal-body">
          <p><strong>사용자:</strong> {{ editingUser?.loginId }} ({{ editingUser?.email }})</p>
          <div class="form-group">
            <label>새 등급:</label>
            <select v-model="selectedLevel">
              <option v-for="level in memberLevels" :key="level.value" :value="level.value">
                {{ level.name }}
              </option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-cancel" @click="closeEditModal">취소</button>
          <button class="btn-confirm" @click="updateUserLevel">확인</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.layout {
  min-height: 100vh;
  background: #f5f5f5;
}

.admin-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.header h1 {
  color: #333;
  margin: 0;
}

.search-box {
  display: flex;
  gap: 0.5rem;
}

.search-box input {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
}

.search-box button {
  padding: 0.5rem 1rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.users-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.users-table table {
  width: 100%;
  border-collapse: collapse;
}

.users-table th,
.users-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.users-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.level-badge {
  padding: 0.25rem 0.5rem;
  background: #e3f2fd;
  color: #1976d2;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
}

.btn-edit {
  padding: 0.25rem 0.5rem;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
}

.btn-edit:hover {
  background: #218838;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 2rem;
}

.pagination button {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-top: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
}

.form-group select {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  padding: 1.5rem;
  border-top: 1px solid #eee;
}

.btn-cancel {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.btn-confirm {
  padding: 0.5rem 1rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-confirm:hover {
  background: #0056b3;
}
</style>
